package com.ctw.tinyservices.id.core.snowflake.holder;

import com.ctw.tinyservices.id.common.utils.LogUtils;
import com.ctw.tinyservices.id.core.snowflake.exception.LocalWorkIdNotFoundException;

import java.util.Random;

/**
 * @author TongWei.Chen 2022/4/13 13:41
 *
 * LocalFile
 **/
public class LocalFileIdSnowflakeHolder extends AbstractIdSnowflakeHolder {

    private volatile static LocalFileIdSnowflakeHolder singleton;
    public static LocalFileIdSnowflakeHolder getInstance(Integer port) {
        if (singleton == null) {
            synchronized (LocalFileIdSnowflakeHolder.class) {
                if (singleton == null) {
                    singleton = new LocalFileIdSnowflakeHolder(port);
                }
            }
        }
        return singleton;
    }

    private LocalFileIdSnowflakeHolder(int port) {
        super(port);
    }

    @Override
    protected void doProcess() throws Exception {
        // I know there may be duplicate bugs
        this.workerId = new Random().nextInt(1022) + 1;
    }

    @Override
    protected void doUpdateMaxTimestamp() throws Exception {}

    @Override
    protected void doProcessException(Exception e) {
        LogUtils.error(LocalFileIdSnowflakeHolder.class, "Read local file error ", e);
        throw new LocalWorkIdNotFoundException("local file maybe not exists");
    }
}
